/**
 * Copyright(C) 2008 Matthias Braunhofer
 * All rights reserved
 *
 * Created on: 28.07.2008
*/

package it.cums.wizards;

import it.cums.controller.ApplicationController;
import it.cums.model.Customer;
import it.cums.model.Customers;
import it.cums.util.Converter;
import it.cums.util.OrderManager;

import java.util.Date;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

public class OrderWizard extends Wizard implements IWorkbenchWizard {
	private OrderWizardPage orderWizardPage;
	private Customer customer;
	
	public OrderWizard() {
		super();
		setNeedsProgressMonitor(true);
		setWindowTitle("New Order");
	}
	
	public OrderWizard(Customer customer) {
		super();
		this.customer = customer;
		setNeedsProgressMonitor(true);
		setWindowTitle("New Order");
	}
	
	@Override
	public void addPages() {
		if (customer != null) {
			orderWizardPage = new OrderWizardPage(customer);
		} else {
			orderWizardPage = new OrderWizardPage();
		}
		addPage(orderWizardPage);
	}
	
	@Override
	public boolean performFinish() {
		Customers customers = ApplicationController.getInstance().getCustomers();
		Customer customer = null;
		for (Customer c : customers.getCustomers()) {
			if (c.getName().equals(orderWizardPage.getCustomer())) {
				customer = c;
				break;
			}
		}
		String status = orderWizardPage.getStatus();
		String priority = orderWizardPage.getPriority();
		Date orderDate = null;
		try {
			orderDate = Converter.convertToDate(orderWizardPage.getOrderDate());
		} catch (Exception e) {
		}
		Date deliveryDate = null;
		try {
			deliveryDate = Converter.convertToDate(orderWizardPage.getDeliveryDate());
		} catch (Exception e) {
		}
		double totalPrice = 0;
		int discount = 0;
		double endPrice = 0;
		try {
			OrderManager.getInstance().createAndStoreOrder(customer.getOrders(), status, customer, priority, orderDate, deliveryDate, totalPrice, discount, endPrice);			
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public void init(IWorkbench arg0, IStructuredSelection arg1) {
	}
}
